package querysrc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

import com.subway.babynote.syncdata.StringUtil;


import serverdata.ServerDataRecord;


public class query_FeedSync extends query {

	public query_FeedSync(sqlConnectionHandler sqlconhandler)
	{
		super(sqlconhandler);
	}	
	
	public int InsertFeedsRecord(List<ServerDataRecord.feedRecord> records, int user_id)
	{

		querydb qdb = null;
		Connection con = null;
		
		try
		{
			boolean bret = true;
			con = this.init();	
			int iret = -1;
			int count = 0;
			int maxts = 0;
			if(bret)
			{
				maxts = this.getMaxts(con,user_id);
			}
			if(!this.needInsert(records, maxts))
			{
				iret = 0;
				return iret;
			}
			if(bret)
			{
				con.setAutoCommit(false);
				qdb = new querydb(con,sqlscripts.sql_insert_feeds_record);			
				bret = qdb.prePS();
			}
			if(bret)
			{
				Iterator<ServerDataRecord.feedRecord> it = records.iterator();
				while(it.hasNext())
				{
					ServerDataRecord.feedRecord fr = it.next();
					if(fr.ts > maxts)
					{
						this.setPSparam(qdb.ps, fr);
						iret = qdb.execPSInsert();
						count++;
					}
				}
				con.commit();				
			}			
			return count;
		}
		catch(SQLException se) {
		      System.out.println("SQLException: "+se.getMessage());
		      return -1;
	    }
		catch(Exception e)
		{
			e.printStackTrace();
			return -1;
		}
		finally
		{
			this.release_querydb(qdb);
			this.release_connection(con);
			this.finalize();
		}
	}
	
	private boolean needInsert(List<ServerDataRecord.feedRecord> records, int maxts)
	{
		Iterator<ServerDataRecord.feedRecord> it = records.iterator();
		while(it.hasNext())
		{
			ServerDataRecord.feedRecord fr = it.next();
			if(fr.ts > maxts)
				return true;			
		}
		return false;
	}
	
	private int getMaxts(Connection con,int user_id)
	{
		return this.getMaxts_base(con, user_id, sqlscripts.sql_feeds_max_ts_select,
				sqlscripts.sql_feeds_max_ts_select_c1);
	}
	
	private int setPSparam(PreparedStatement ps, ServerDataRecord.feedRecord fr)
	{
		//(food_id , user_id , r_date , r_time , quantity ,ts )
		try
		{
			ps.setInt(1, fr.food_id);
			ps.setInt(2, fr.user_id);
			ps.setDate(3, fr.r_time);
			ps.setString(4, StringUtil.date2str(fr.r_time));			
			ps.setFloat(5, fr.quantity);
			ps.setInt(6, fr.ts);
			return 0;
		}
		catch(SQLException se) {
		      System.out.println("SQLException: "+se.getMessage());
		      return -1;
	    }
		catch(Exception e)
		{
			e.printStackTrace();
			return -1;
		}
	}
}
